﻿using System;
using System.Web;
using System.Data;
using System.Text;
using System.Text.RegularExpressions;

/// <summary>
/// 通用工具类
/// </summary>
public class Tools
{
	public Tools()
	{ }

    /// <summary> 
    /// 根据 Agent 判断是否是智能手机 
    /// </summary> 
    /// <returns></returns> 
    public static bool CheckAgent()
    {
        bool flag = false;
        try
        {
            string agent = HttpContext.Current.Request.UserAgent;
            string[] keywords = { "Android", "iPhone", "iPod", "iPad", "Windows Phone", "MQQBrowser" };
            //排除Window 桌面系统 和 苹果桌面系统 
            if (!agent.Contains("Windows NT") || (agent.Contains("Windows NT") && agent.Contains("compatible; MSIE 9.0;")))
            {
                if (!agent.Contains("Windows NT") && !agent.Contains("Macintosh"))
                {
                    foreach (string item in keywords)
                    {
                        if (agent.Contains(item))
                        {
                            flag = true;
                            break;
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            log4net.LogManager.GetLogger("").Error("工具类智能手机判断异常！"+ex.Message);
        }
        return flag;
    }

    /// <summary>
    /// 获取客户端IP
    /// </summary>
    /// <returns></returns>
    public static string GetClientIP()
    {
        string result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
        if (null == result || result == String.Empty)
        {
            result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
        }
        if (null == result || result == String.Empty)
        {
            result = HttpContext.Current.Request.UserHostAddress;
        }
        return result;
    }

    /// <summary>
    /// MD5加密
    /// </summary>
    /// <param name="argPass"></param>
    /// <returns></returns>
    public static string EncryptPasswordByMD5(string argPass)
    {
        return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(argPass, "MD5");
    }

    /// <summary>
    /// 过滤字符串中的非法字符串
    /// </summary>
    /// <param name="text"></param>
    /// <param name="maxLength"></param>
    /// <returns></returns>
    public static string ReplaceString(string text, int maxLength)
    {
        #region
        text = text.Trim();
        if (string.IsNullOrEmpty(text))
            return string.Empty;
        if (text.Length > maxLength)
            text = text.Substring(0, maxLength);
        text = Regex.Replace(text, "[\\s]{2,}", " "); //two or more spaces
        text = Regex.Replace(text, "(<[b|B][r|R]/*>)+|(<[p|P](.|\\n)*?>)", "\n"); //<br>
        text = Regex.Replace(text, "(\\*)+", " "); //&nbsp;
        text = Regex.Replace(text, "<(.|\\n)*?>", string.Empty);
        text = text.Replace("'", "''");
        return text;
        #endregion
    }

    /// <summary>
    /// 导出EXCEL
    /// </summary>
    /// <param name="ctl"></param>
    public static void DGToExcel(System.Web.UI.Control ctl,string argEncode)
    {
        HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=Excel.xls");
        HttpContext.Current.Response.Charset = argEncode;
        HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding(argEncode);
        HttpContext.Current.Response.ContentType = "application/ms-excel";
        ctl.Page.EnableViewState = false;
        System.IO.StringWriter tw = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
        ctl.RenderControl(hw);
        HttpContext.Current.Response.Write(tw.ToString());
        HttpContext.Current.Response.End();
    }

    public static void DGToExcel(System.Web.UI.Control ctl, System.Web.UI.Control ctl2)
    {
        HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=Excel.xls");
        HttpContext.Current.Response.Charset = "UTF-8";
        HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
        HttpContext.Current.Response.ContentType = "application/ms-excel";
        ctl.Page.EnableViewState = false;
        ctl2.Page.EnableViewState = false;
        System.IO.StringWriter tw = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
        ctl.RenderControl(hw);
        ctl2.RenderControl(hw);
        HttpContext.Current.Response.Write(tw.ToString());
        HttpContext.Current.Response.End();
    }

    /// <summary>  
    /// dataTable转换成Json格式  
    /// </summary>  
    /// <param name="dt"></param>  
    /// <returns></returns>  
    public static string DataTableToJson(DataTable dtChild)
    {
        StringBuilder jsonBuilder = new StringBuilder();
        jsonBuilder.Append("[");
        for (int i = 0; i < dtChild.Rows.Count; i++)
        {
            //jsonBuilder.Append("{");
            for (int j = 0; j < dtChild.Columns.Count; j++)
            {
                /*jsonBuilder.Append("");
                jsonBuilder.Append(dtChild.Columns[j].ColumnName);
                jsonBuilder.Append(":\"");
                jsonBuilder.Append(dtChild.Rows[i][j].ToString());
                jsonBuilder.Append("\",");*/
                jsonBuilder.Append("\"");
                jsonBuilder.Append(dtChild.Rows[i][j].ToString());
                jsonBuilder.Append("\",");
            }
            //jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
            //jsonBuilder.Append("},");
        }
        jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
        jsonBuilder.Append("]");
         return jsonBuilder.ToString();
    }
}
